//
//  CBWebViewController.swift
//  jrw
//
//  Created by cabinzhao on 3/24/17.
//  Copyright © 2017 武汉玖信普惠金融信息服务有限公司. All rights reserved.
//

import UIKit
import WebKit

class CBWebViewController: CBBaseViewController, UIWebViewDelegate, WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler {
    
    //传入得参数 下面两个必传一个
    var urlAddress:String = ""
    var htmlString:String = ""
    
    //是否需要加在JSPOST接口的方法
    var isNeedLoadJSPOST = false
    var postParam:[String:Any] = [String:Any]()
    
    var webView:WKWebView!
    var progressView:UIProgressView?
    private var loadCount:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.edgesForExtendedLayout = .all
        self.extendedLayoutIncludesOpaqueBars = true
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.setupView()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        if self.progressView != nil {
            self.progressView?.removeFromSuperview()
            self.progressView = nil
        }
        super.viewWillDisappear(animated)
    }
    
    var isDirectBack:Bool = false;
    override func backAction() {
        let cnt = self.webView.backForwardList.backList.count
        if cnt > 0 && isDirectBack == false {
            self.webView.goBack()
        } else {
            //清除缓存
            if #available(iOS 9.0, *) {
                let setType = Set([WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache])
                let dateFrom = Date.init(timeIntervalSince1970: 0)
                WKWebsiteDataStore.default().removeData(ofTypes: setType, modifiedSince: dateFrom) {}
            } else {
                // Fallback on earlier versions
                let cookiePath = NSHomeDirectory() + "/Library/Cookies"
                try? FileManager.default.removeItem(atPath: cookiePath)
            }
            super.backAction()
        }
    }
    
    private func setupView() {
        self.view.backgroundColor = UIColor.white
        //进度条
        progressView = UIProgressView()
        progressView?.cb_size = CGSize(width: Screen.width, height: 2)
        progressView?.cb_top = ((Screen.height == 812.0) ? 88 : 64) - 2
        progressView?.progressTintColor = UIColor(hex:0x02c602)
        progressView?.trackTintColor = UIColor(hex:0xffffff)
        self.navigationController?.view.addSubview(progressView ?? UIView())
        
        //配置信息
        let configuration = WKWebViewConfiguration()
        configuration.preferences = WKPreferences()
        configuration.preferences.javaScriptEnabled = true
        configuration.processPool = WKProcessPool()
        configuration.userContentController = WKUserContentController()
        configuration.userContentController.add(self, name: "PopAction")
        
        //网页控件
        webView = WKWebView(frame: .zero, configuration: configuration)
        webView.cb_size = CGSize(width: Screen.width, height: Screen.height - ((Screen.height == 812.0) ? 88 : 64))
        webView.cb_top = progressView?.cb_bottom ?? 0
        
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        
        //需要通过JS间接加载
        if isNeedLoadJSPOST {
            // 获取JS路径
            let path = Bundle.main.path(forResource: "JSPOST", ofType: "html")
            do {
                let html = try String(contentsOfFile: path!, encoding: .utf8)
                // 加载js
                webView.loadHTMLString(html, baseURL: Bundle.main.bundleURL)
            } catch { }
            
        } else { //无需加在POST参数
            if !urlAddress.isEmpty {
                let request = URLRequest(url: URL(string: urlAddress)!)
                webView.load(request)
            } else if !htmlString.isEmpty {
                webView.loadHTMLString(htmlString, baseURL: nil)
            }
        }
        self.view.addSubview(webView)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress"  {
            self.progressView?.alpha = 1.0
            self.progressView?.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.webView.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: { [unowned self] in
                    self.progressView?.alpha = 0.0
                    }, completion: { (flag) in
                        self.progressView?.setProgress(0.0, animated: false)
                })
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    //JS代码调用Native接口
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let msgBody = message.body as? String ?? ""
        switch message.name {
        case "PopAction":
            self.popAction(msgBody: msgBody)
            break;
        default:
            break;
        }
    }
    
    //返回事件
    func popAction(msgBody:String) {
        isDirectBack = true
        if msgBody == "" || msgBody == "chargeMoney" { //充值
            self.backLevel = 2
        } else if msgBody == "getCGSetPwdPage" { //第一次设置交易密码
            self.backLevel = 3
        } else if msgBody == "cashMoney" { //提现
            self.backLevel = 1
        } else if msgBody == "phoneBinding" { //手机绑定
            self.backLevel = 2 //默认
        } else if msgBody == "openAutoAuthorize" { //设置自动授权
            self.backLevel = 1
        } else if msgBody == "tradingPassword" { //第二次或以后设置交易密码
            self.backLevel = 1
        } else if msgBody == "bindingPage" { //绑定银行卡页面回调
            self.backLevel = 1
        } else {
            self.backLevel = 1
        }
        self.backAction()
    }
    
    // 加载完成的代理方法
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if isNeedLoadJSPOST {
            // 拼装成调用JavaScript的字符串
            let jscript = "post('\(self.urlAddress)', \(self.postParam.jsonString));"
            // 调用JS代码
            webView.evaluateJavaScript(jscript) { (object, error) in}
            isNeedLoadJSPOST = false
        }
        
    }
    
    //兼容Alert
    //Alert弹框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert)
        let action = UIAlertAction(title: "好的", style: UIAlertActionStyle.cancel) { (_) in
            completionHandler()
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    //confirm弹框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert)
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (_) in
            completionHandler(true)
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (_) in
            completionHandler(false)
        }
        alert.addAction(action)
        alert.addAction(cancelAction)
        present(alert, animated: true, completion: nil)
    }
    //TextInput弹框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController(title: "", message: nil, preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField { (_) in}
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (_) in
            completionHandler(alert.textFields?.last?.text)
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.navigationDelegate = nil
        self.webView.uiDelegate = nil
    }
    
    
}

